from PyQt6.QtWidgets import (
    QMainWindow, QVBoxLayout, QWidget, 
    QFrame, QGraphicsDropShadowEffect
)
from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QColor
from .main_layout import MainLayout
from ..global_style.colors import Colors
from ..components.title_bar import TitleBar
from ..components.shadow_effect import add_window_shadow
import json
import os

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        # 加载配置
        self.config = self._load_config()
        
        # 设置窗口基本属性
        self.setWindowTitle(self.config["window"]["title"])
        self.setMinimumSize(QSize(
            self.config["window"]["width"], 
            self.config["window"]["height"]
        ))
        
        # 设置无边框窗口并允许透明背景以显示圆角
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 创建一个外部容器
        self.outer_container = QWidget()
        self.setCentralWidget(self.outer_container)
        
        # 创建外部布局，添加边距以容纳阴影
        self.outer_layout = QVBoxLayout(self.outer_container)
        self.outer_layout.setContentsMargins(10, 10, 10, 10)  # 为阴影预留空间
        self.outer_layout.setSpacing(0)
        
        # 创建一个内部框架作为实际的窗口容器
        self.window_frame = QFrame()
        self.window_frame.setObjectName("windowFrame")
        self.outer_layout.addWidget(self.window_frame)
        
        # 添加阴影效果
        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(20)
        self.shadow.setXOffset(0)
        self.shadow.setYOffset(0)
        self.shadow.setColor(QColor(0, 0, 0, 50))  # 最后一个参数是透明度(0-255)
        self.window_frame.setGraphicsEffect(self.shadow)
        
        # 创建内部布局
        self.inner_layout = QVBoxLayout(self.window_frame)
        self.inner_layout.setContentsMargins(0, 0, 0, 0)
        self.inner_layout.setSpacing(0)
        
        # 添加标题栏
        self.title_bar = TitleBar(self)
        self.inner_layout.addWidget(self.title_bar)
        
        # 添加内容区域
        self.content = MainLayout()
        self.inner_layout.addWidget(self.content)
        
        # 加载样式表
        self._load_stylesheets()
        
    def _load_config(self):
        """加载配置文件"""
        # 获取当前文件所在目录
        current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        config_path = os.path.join(current_dir, "config.json")
        
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            # 返回默认配置
            return {
                "window": {
                    "title": "默认标题",
                    "width": 800,
                    "height": 600,
                    "border_radius": 10,
                    "background_color": "white"
                }
            }
    
    def _load_stylesheets(self):
        """加载样式表"""
        try:
            style_files = [
                "global_style/global_style.qss",
                "global_style/components.qss",
                "left_main/style.qss",
                "right_main/style.qss",
                "main/main_style.qss"
            ]
            
            combined_style = ""
            for style_file in style_files:
                file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), style_file)
                with open(file_path, "r", encoding="utf-8") as f:
                    combined_style += f.read() + "\n"
            
            # 替换样式变量
            combined_style = combined_style.replace(
                "{border_radius}", str(self.config["window"]["border_radius"])
            )
            
            self.setStyleSheet(combined_style)
        except Exception as e:
            print(f"加载样式表失败: {e}")
        
    def mousePressEvent(self, event):
        """实现窗口拖动"""
        if event.button() == Qt.MouseButton.LeftButton:
            self._drag_pos = event.globalPosition().toPoint()

    def mouseMoveEvent(self, event):
        """实现窗口拖动"""
        if hasattr(self, '_drag_pos'):
            diff = event.globalPosition().toPoint() - self._drag_pos
            newpos = self.pos() + diff
            self.move(newpos)
            self._drag_pos = event.globalPosition().toPoint()

    def mouseReleaseEvent(self, event):
        """实现窗口拖动"""
        if hasattr(self, '_drag_pos'):
            delattr(self, '_drag_pos')